package cn.lingyangwl.agile.infra.weixin.mp.service.impl;

import cn.hutool.core.lang.Assert;
import cn.lingyangwl.agile.infra.weixin.mp.assembly.MpMessageAssembly;
import cn.lingyangwl.agile.infra.weixin.mp.constants.MpMessageSendFromEnum;
import cn.lingyangwl.agile.infra.weixin.mp.manager.MpMessageManager;
import cn.lingyangwl.agile.infra.weixin.mp.manager.MpUserManager;
import cn.lingyangwl.agile.infra.weixin.mp.model.entity.MpMessage;
import cn.lingyangwl.agile.infra.weixin.mp.model.entity.MpUser;
import cn.lingyangwl.agile.infra.weixin.mp.model.rqrs.MpMessageSendOutReq;
import cn.lingyangwl.agile.infra.weixin.mp.handler.WxMpHandler;
import cn.lingyangwl.agile.infra.weixin.mp.service.MpMessageService;
import cn.lingyangwl.agile.infra.weixin.mp.utils.MpUtils;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.Validator;
import java.util.Objects;

/**
 * @author shenguangyang
 */
@Service
public class MpMessageServiceImpl implements MpMessageService {
    @Resource
    private Validator validator;

    @Resource
    private MpMessageAssembly mpMessageAssembly;

    @Resource
    private MpUserManager mpUserManager;

    @Resource
    private MpMessageManager mpMessageManager;

    @Resource
    @Lazy
    private WxMpHandler mpProcess;

    @Override
    public void receiveMessage(String appId, WxMpXmlMessage wxMessage) {
        // 获得关联信息
        MpUser user = mpUserManager.getUser(appId, wxMessage.getFromUser());
        if (Objects.isNull(user) && WxConsts.EventType.SUBSCRIBE.equals(wxMessage.getEventKey())) {
            return;
        }
        Assert.notNull(user, "公众号粉丝 [{}/{}] 不存在", appId, wxMessage.getFromUser());

        // 记录消息
        MpMessage message = mpMessageAssembly.toMpMessage(wxMessage, user)
                .setSendFrom(MpMessageSendFromEnum.USER_TO_MP.getFrom());
        message.setMpAppId(appId);
//        downloadMessageMedia(message);
        mpMessageManager.save(message);
    }

    @Override
    public WxMpXmlOutMessage sendOutMessage(MpMessageSendOutReq req) {
        // 校验消息格式
        MpUtils.validateMessage(validator, req.getType(), req);

        // 获得关联信息
        MpUser user = mpUserManager.getUser(req.getAppId(), req.getOpenId());
        Assert.notNull(user, "公众号粉丝({}/{}) 不存在", req.getAppId(), req.getOpenId());

        // 记录消息
        MpMessage message = mpMessageAssembly.toMpMessage(req, mpProcess.getContext().getMpParam(), user).
                setSendFrom(MpMessageSendFromEnum.MP_TO_USER.getFrom());
//        downloadMessageMedia(message);
        mpMessageManager.save(message);
        return mpMessageAssembly.toWxMpXmlOutMessage(message);
    }
}
